#include "Stack.h"

void StackInit(ST* ps)
{
	ps->arr = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

void StackDestroy(ST* ps)
{
	if (ps->arr)
		free(ps->arr);
	ps->arr = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

void StackPush(ST* ps, STDataType x)
{
	assert(ps != NULL);
	if (ps->top == ps->capacity) {
		int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		STDataType* tmp = (STDataType*)realloc(ps->arr, newCapacity * sizeof(STDataType));
		if (tmp == NULL) {
			perror("StackPush()::realloc");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newCapacity;
	}
	ps->arr[ps->top++] = x;
}

bool STEmpty(ST* ps)
{
	assert(ps != NULL);
	return ps->top == 0;
}

void StackPop(ST* ps)
{
	assert(!STEmpty(ps));
	--(ps->top);
}

STDataType StackTop(ST* ps)
{
	assert(!STEmpty(ps));
	return ps->arr[ps->top - 1];
}

int StackSize(ST* ps)
{
	assert(ps != NULL);
	return ps->top;
}

